package com.easylinkin.linkappapi.quality.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.service.CommonService;
import com.easylinkin.linkappapi.common.utils.excel.ExcelConstant;
import com.easylinkin.linkappapi.common.utils.excel.ExcelTools;
import com.easylinkin.linkappapi.common.utils.io.OutputStreamUtil;
import com.easylinkin.linkappapi.quality.dto.QualityQuestionCommentDto;
import com.easylinkin.linkappapi.quality.entity.QualityQuestionComment;
import com.easylinkin.linkappapi.quality.entity.vo.QualityQuestionCommentVo;
import com.easylinkin.linkappapi.quality.mapper.QualityQuestionCommentMapper;
import com.easylinkin.linkappapi.quality.service.QualityQuestionCommentService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * QualityQuestionComment表服务实现类
 *
 * @author zhengwen
 * @date 2022/08/16
 */
@Slf4j
@Service("appQualityQuestionCommentService")
public class QualityQuestionCommentServiceImpl extends ServiceImpl
        <QualityQuestionCommentMapper, QualityQuestionComment> implements QualityQuestionCommentService {
    @Resource
    private CommonService commonService;
    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;

    @Override
    public boolean saveOne(QualityQuestionComment questionComment) {
        LinkappUser appUser = linkappUserContextProducer.getNotNullCurrent();

        //参数校验
        cn.hutool.core.lang.Assert.isFalse(StringUtils.isBlank(questionComment.getContent()),"评论内容不能为空");

        questionComment.setCreateTime(DateUtil.date());
        questionComment.setDeleteState(1);
        questionComment.setCreator(appUser.getId().toString());
        commonService.setCreateAndModifyInfo(questionComment);
        return save(questionComment);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOne(QualityQuestionComment appQualityQuestionComment) {
        Assert.notNull(appQualityQuestionComment.getId(), "id不能为空");
        commonService.setModifyInfo(appQualityQuestionComment);
        //appQualityQuestionComment.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        validRepeat(appQualityQuestionComment);
        validParamFormat(appQualityQuestionComment);
        return updateById(appQualityQuestionComment);
    }

    @Override
    public IPage<QualityQuestionComment> selectPage(Page page, QualityQuestionComment appQualityQuestionComment) {
        //appQualityQuestionComment.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        return baseMapper.selectPage(page, appQualityQuestionComment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(List<Long> idList) {
        return removeByIds(idList);
    }

    @Override
    public void export(QualityQuestionComment appQualityQuestionComment, HttpServletRequest request, HttpServletResponse
            response) {

        IPage<QualityQuestionComment> page = selectPage(new Page(0, -1), appQualityQuestionComment);
        List<QualityQuestionComment> records = page.getRecords();
        List
                <QualityQuestionCommentVo> appQualityQuestionCommentVos = new ArrayList<>();
        for (QualityQuestionComment expert : records) {
            appQualityQuestionCommentVos.add(new QualityQuestionCommentVo(expert));
        }

        String keyValue = "名称:name,租户id:tenantId";
        String title = "QualityQuestionComment导出数据";
        String fileName = title + ".xls";
        try {
            OutputStream outputStream = OutputStreamUtil
                    .getOutputStream(request, response, fileName);
            ExcelTools.exportExcel(outputStream, keyValue, appQualityQuestionCommentVos, ExcelConstant.XLS, title);
            response.flushBuffer();
            outputStream.close();
        } catch (IOException e) {
            log.error("excel导出失败", e);
            throw new RuntimeException("excel导出失败！IOException异常" + e.getMessage());
        } catch (Exception e) {
            log.error("excel导出失败", e);
            throw new RuntimeException("excel导出失败！" + e.getMessage());
        }
    }

    @Override
    public RestMessage getQuestionComment(Long questionId) {
        cn.hutool.core.lang.Assert.isFalse(questionId == null,"问题id为空");
        List<QualityQuestionCommentDto> commentDtoList = this.baseMapper.getQuestionComment(questionId);
        return RestBuilders.successBuilder().data(commentDtoList).build();
    }

    @Override
    public RestMessage getQuestionCommentFromEnterprise(Long questionId) {
        cn.hutool.core.lang.Assert.isFalse(questionId == null, "问题id为空");
        List<QualityQuestionCommentDto> commentDtoList = this.baseMapper.getQuestionComment(questionId);
        return RestBuilders.successBuilder().data(commentDtoList).build();
    }

    @Override
    public QualityQuestionComment getOneById(Serializable id) {
        return baseMapper.getOneById(id);
    }

    /**
     * 校验重复
     */
    private void validRepeat(QualityQuestionComment appQualityQuestionComment) {
        /* QueryWrapper<QualityQuestionComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", appQualityQuestionComment.getName());
        queryWrapper.eq("tenant_id", linkappUserContextProducer.getNotNullCurrent().getTenantId());
        List<QualityQuestionComment> list = baseMapper.selectList(queryWrapper);
        if (list.size() == 0) {
            return;
        }
        if (list.size() > 1) {
            throw new BusinessException("名称有重复");
        }
        if (ObjectUtils.isEmpty(appQualityQuestionComment.getId())) {
            throw new BusinessException("名称已存在");
        }
        if (!appQualityQuestionComment.getId().equals(list.get(0).getId())) {
            throw new BusinessException("名称已存在");
        }
                    */

    }


    /**
     * 校验参数必填
     */
    private void validParamRequired(QualityQuestionComment appQualityQuestionComment) {
        //Assert.notNull(appQualityQuestionComment, "参数为空");
        //Assert.isTrue(StringUtils.isNotBlank(appQualityQuestionComment.getName()), "名称为空");
    }

    /**
     * 校验参数格式
     */
    private void validParamFormat(QualityQuestionComment appQualityQuestionComment) {
        //Assert.isTrue(appQualityQuestionComment.getName() == null || appQualityQuestionComment.getName().length() <= 50,
        //        "名称超长");
    }
}

